package leetcode;

public class BinaryAdd {

	public static void main(String[] args) {
		System.out.println(addBinary("111100", "111"));
	}
	
	//bad idea
	public static String addBinary(String a, String b) {
        if(a == null || b == null){
            return null;
        }
        char[] snumber1 = a.toCharArray();
        char[] snumbers = b.toCharArray();
        int[] num1 = new int[snumber1.length];
        int[] num2 = new int[snumbers.length];
        //注意，char数组中最低位存放着二进制的最高位
        for(int i = 0; i < snumber1.length; i++){
            num1[i] = (snumber1[snumber1.length - 1 - i] == '0' ? 0 : 1);
        }
        for(int i = 0; i < snumbers.length; i++){
            num2[i] = (snumbers[snumbers.length - 1 - i] == '0' ? 0 : 1);
        }
        int len = Math.min(snumber1.length, snumbers.length);
        int maxlen = Math.max(snumber1.length, snumbers.length);
       // final int indicator = s1.length - s2.length >= 0 ? 0 : -1;
        int[] sum = new int[maxlen];
        int carry = 0;
        for(int i = 0; i < len; i++){
            carry = num1[i] + num2[i] + carry;
            sum[i] = carry & 1;
            carry = carry >> 1;
        }
        final int indicator = snumber1.length > len ? 0 : -1;
        for(int i = len; i < maxlen; i++){
        	if(indicator == 0){
        		carry = num1[i] + carry;
        	}else {
        		carry = num2[i] + carry;
			}
            sum[i] = carry & 1;
            carry = carry >> 1;
        }
        for (int i = 0; i < sum.length; i++) {
			System.out.println(sum[i] + " ");
		}
        if(carry == 1){
            char[] result = new char[maxlen + 1];
            for(int i = maxlen; i > 0; i--){
                result[maxlen + 1 - i] = sum[i - 1] == 0 ? '0' : '1';
            }
            result[0] = '1';
            return String.valueOf(result);
        }else{
            char[] result = new char[maxlen];
            for(int i = maxlen - 1; i >= 0; i--){
                result[maxlen - 1 - i] = sum[i] == 0 ? '0' : '1';
            }
            return String.valueOf(result);
        }
    }
}
